package iip

import (
    "github.com/gin-gonic/gin"
    "iip/iip/model"
)

func (s *IIP) WeightRecordPagedList(c *gin.Context) {

    query := &struct {
        Page     int    `form:"page" binding:"required,gte=1" json:"page"`
        PageSize int    `form:"pagesize" binding:"required,gte=1" json:"pagesize"`
        Order    string `form:"order" json:"order"`
    }{}
    if err := c.ShouldBindQuery(query); err != nil {
        s.logger.Error(err.Error())
        s.json_error(c, err.Error())
        return
    }
    if query.Order != "asc" && query.Order != "desc" {
        query.Order = "asc"
    }


    var total int64
    if err := s.gorm().Model(&model.WeightRecord{}).Count(&total).Error; err != nil {
        s.logger.Error(err.Error())
        s.json_error(c, err.Error())
        return
    }

    var row_lst []*model.WeightRecord
    if err := s.gorm().Limit(query.PageSize).Offset(query.PageSize * (query.Page - 1)).Order("id " + query.Order).Find(&row_lst).Error; err != nil {
        s.logger.Error(err.Error())
        s.json_error(c, err.Error())
        return
    }

    var lst []interface{}
    for _, row := range row_lst {
        truck, err := s.dict.GetTruckByID(row.TruckID)
        if err != nil {
            s.logger.Error(err)
            s.json_error(c, err.Error())
            return
        }
        wb, err := s.dict.GetWeighbridgeByID(row.WeighbridgeID)
        if err != nil {
            s.logger.Error(err)
            s.json_error(c, err.Error())
            return
        }

        lst = append(lst, s.WeightRecordFull(row, truck, wb))
    }
    s.logger.Info("query weighrecord paged list")
    s.json_paged_data(c, total, query.Page, query.PageSize, lst)
}

func (s *IIP) WeightRecordByID(c *gin.Context) {
    req := &struct {
        ID int64 `uri:"id"`
    }{}
    if err := c.ShouldBindUri(req); err != nil {
        s.logger.Error(err.Error())
        s.json_error(c, err.Error())
        return
    }

    row, err := s.GetWeightRecordByID(req.ID)
    if err != nil {
        s.logger.Error(err.Error())
        s.json_error(c, err.Error())
        return
    }
    truck, err := s.dict.GetTruckByID(row.TruckID)
    if err != nil {
        s.logger.Error(err)
        s.json_error(c, err.Error())
        return
    }
    wb, err := s.dict.GetWeighbridgeByID(row.WeighbridgeID)
    if err != nil {
        s.logger.Error(err)
        s.json_error(c, err.Error())
        return
    }

    s.logger.Info("query weighbridge by id ", req.ID)
    s.json_data(c, s.WeightRecordFull(row, truck, wb))
}
